package com.boby.homecamera.activity.client

import android.app.Activity
import android.app.ActivityOptions
import android.content.Intent
import android.os.Build
import android.os.Bundle
import android.view.View
import android.widget.EditText
import android.widget.TextView
import androidx.activity.result.ActivityResultLauncher
import androidx.appcompat.app.AppCompatActivity
import androidx.appcompat.widget.Toolbar
import com.boby.homecamera.R
import com.boby.homecamera.activity.LauncherActivity
import com.boby.homecamera.config.AppConfig
import com.boby.homecamera.constant.Constant
import com.boby.homecamera.db.CameraDeviceTable.CameraDevice
import com.boby.homecamera.db.ClientDBManager
import com.boby.homecamera.net.Api
import com.boby.homecamera.net.Api.getRealUrl
import com.boby.homecamera.webserver.model.UserInfo
import com.boby.lib_common.base.BaseActivity
import com.boby.lib_common.extens.toast
import com.boby.lib_common.network.Net
import com.boby.lib_common.util.BLog
import com.boby.lib_common.util.MD5
import com.lxj.xpopup.XPopup
import com.lxj.xpopup.interfaces.OnConfirmListener

class CameraEditActivity : BaseActivity() {
    private val TAG = "CameraEditActivity"
    companion object{
        /**
         * type: 0 新增设备，1：编辑设备
         */
        fun start(activity: AppCompatActivity,type:Int,activityResultLauncher: ActivityResultLauncher<Intent>,cameraData:CameraDevice? = null ){
            val intent = Intent(activity, CameraEditActivity::class.java)
            intent.putExtra("type",type)
            if(type == 1){
                if(cameraData != null){
                    intent.putExtra("data",cameraData)
                }else{
                    return
                }
            }
            activityResultLauncher.launch(intent)

        }
    }
    private var type = 0 //0 新增设备，1：编辑设备
    private var cameraData:CameraDevice? = null
    private lateinit var et_camera_device_name: EditText
    private lateinit var et_camera_device_ip: EditText
    private lateinit var et_user_name: EditText
    private lateinit var et_user_password: EditText
    private lateinit var et_http_port: EditText
    private lateinit var et_stream_port: EditText
    private lateinit var et_websocket_port: EditText
    private lateinit var tv_title: TextView
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_edit_camera_devices)

        val toolbar: Toolbar = findViewById(R.id.mToolbar)
        setSupportActionBar(toolbar)
        supportActionBar?.setDisplayHomeAsUpEnabled(true) // 显示返回按钮
        initToolBar(toolbar)

        initView()
        initData()
    }

    override fun onSupportNavigateUp(): Boolean {
        finish()
        return true
    }

    private fun initView(){
        tv_title = findViewById(R.id.tv_title)
        et_camera_device_name = findViewById(R.id.et_camera_device_name)
        et_camera_device_ip = findViewById(R.id.et_camera_device_ip)
        et_user_name = findViewById(R.id.et_user_name)
        et_user_password = findViewById(R.id.et_user_password)
        et_http_port = findViewById(R.id.et_http_port)
        et_stream_port = findViewById(R.id.et_stream_port)
        et_websocket_port = findViewById(R.id.et_websocket_port)
    }

    private fun initData(){
        type = intent.getIntExtra("type",0)
        if(type == 0){
            tv_title.text = "添加设备"
        }else{
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
                cameraData = intent.getParcelableExtra("data", CameraDevice::class.java)
            }else{
                cameraData = intent.getParcelableExtra("data")
            }
            tv_title.text = "编辑设备"
            et_camera_device_name.setText("${cameraData?.deviceName}")
            et_camera_device_ip.setText("${cameraData?.ip}")
            et_user_name.setText("${cameraData?.userName}")
            et_user_password.setText("${cameraData?.password}")
            et_http_port.setText("${cameraData?.httpPort}")
            et_stream_port.setText("${cameraData?.streamPort}")
            et_websocket_port.setText("${cameraData?.websocketPort}")
        }


    }

    fun commit(view: View) {
        val deviceName = et_camera_device_name.text.toString()
        val ip = et_camera_device_ip.text.toString()
        val userName = et_user_name.text.toString()
        val password = et_user_password.text.toString()
        val httpPort = et_http_port.text.toString()
        val streamPort = et_stream_port.text.toString()
        val websocketPort = et_websocket_port.text.toString()
        if(deviceName.isBlank()){
            toast("请输入设备名称")
            return
        }
        if(ip.isBlank()){
            toast("请输入服务端ip")
            return
        }
        if(userName.isBlank()){
            toast("请输入账号")
            return
        }
        if(password.isBlank()){
            toast("请输入密码")
            return
        }
        if(httpPort.isBlank()){
            toast("请输入http端口")
            return
        }
        if(streamPort.isBlank()){
            toast("请输入rtp流端口")
            return
        }
        if(websocketPort.isBlank()){
            toast("请输入websocket端口")
            return
        }

        showLoading("")

        Api.login(getRealUrl(ip,httpPort.toInt()),userName,MD5.digest(password),object : Net.CallBack<UserInfo>{
            override fun onSuccess(result: UserInfo) {
                // 查询数据库中已经有的数据
                var queryCamera = ClientDBManager.instance.tb_camrea_device.queryByDeviceId(result.deviceId)
                if(queryCamera != null && type == 0){
                    hideLoading()
                    //已添加过该设备，是否更新该设备信息
                    XPopup.Builder(this@CameraEditActivity)
                        .asConfirm("提示","已添加过该设备，是否更新该设备信息","取消","确定",object : OnConfirmListener{
                            override fun onConfirm() {
                                type = 1
                                cameraData = queryCamera
                                saveData(ip,deviceName,userName,password, result.token,result.deviceId,httpPort.toInt(),streamPort.toInt(),websocketPort.toInt())
                            }
                        },null,false)
                    return
                }
                saveData(ip,deviceName,userName,password, result.token,result.deviceId,httpPort.toInt(),streamPort.toInt(),websocketPort.toInt())
                hideLoading()
            }

            override fun onError(code: Int, error: String?) {
                BLog.d(TAG,"onError $code ,$error")
                toast(error?:"账号或者密码错误")
                hideLoading()
            }
        })
    }

    private fun saveData(ip:String,deviceName:String,userName:String,password:String,token:String,deviceId:String,httpPort:Int,streamPort:Int,websocketPort:Int ){
        if(cameraData == null){
            cameraData = CameraDevice()
        }
        cameraData!!.deviceName = deviceName
        cameraData!!.ip = ip
        cameraData!!.deviceId = deviceId
        cameraData!!.userName = userName
        cameraData!!.password = password
        cameraData!!.token = token
        cameraData!!.httpPort = httpPort
        cameraData!!.streamPort = streamPort
        cameraData!!.websocketPort = websocketPort
        if(type == 0){
            //新增
           val id = ClientDBManager.instance.tb_camrea_device.insert(cameraData!!)
            if(id<0){
                toast("保存失败")
                return
            }
            cameraData!!.id = id
        }else{
            ClientDBManager.instance.tb_camrea_device.update(cameraData!!)
        }

        val intent = Intent()
        intent.putExtra("type",type)
        intent.putExtra("data",cameraData)
        setResult(Activity.RESULT_OK,intent)

        finish()
    }


}